package com.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.domain.Student;
import com.core.mapper.StudentMapper;
import com.core.resp.AjaxResponse;
import com.core.resp.PageResult;
import com.core.service.StudentService;
import com.core.utils.IdGeneratorSnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author legion
 * @description 针对表【student】的数据库操作Service实现
 * @createDate 2025-06-1 14:32:05
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
        implements StudentService {

    @Autowired
    private StudentMapper studentMapper;


    @Override
    public AjaxResponse addStudent(Student student) {
        try {
            student.setId(IdGeneratorSnowFlake.snowFlakeId());
            studentMapper.insert(student);
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry")) {
                return AjaxResponse.error(405, "此学生已经存在");
            }
            log.error(e.getMessage());
        }
        return AjaxResponse.success(200, "添加成功", null);
    }

    @Override
    public PageResult<Student> getPage(Long pageSize, Long pageNum, Student student) {
        Long startIndex = (pageNum - 1) * pageSize;
        List<Student> data = studentMapper.getPage(pageSize, startIndex, student);
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        if (student != null && !student.getStudentName().isEmpty()) {
            queryWrapper.eq(Student::getStudentName, student.getStudentName());
        }
        if (student != null && !student.getStudentIdCard().isEmpty()) {
            queryWrapper.eq(Student::getStudentIdCard, student.getStudentIdCard());
        }
        Long total = studentMapper.selectCount(queryWrapper);
        PageResult<Student> result = new PageResult<>(pageSize, pageNum, data, total);
        return result;
    }
}




